﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using IFDB.Models.Contexts;
using IFDB.ResourceLibrary;

namespace IFDB.Models.Tables
{
    public class Venue
    {
        public Venue()
        {
            this.LookupVenues = new HashSet<LookupVenue>();
            this.Matches = new HashSet<Match>();
        }

        [Key]
        public Guid VenueId { get; set; }
        public Country Country { get; set; }

        [StringLength(50)]
        public string VenueName { get; set; }

        public virtual ICollection<LookupVenue> LookupVenues { get; set; }
        public virtual ICollection<Match> Matches { get; set; }

        public static Venue CreateNew(Country country, string venueName)
        {
            return new Venue()
            {
                VenueId = Guid.NewGuid(),
                Country = country,
                VenueName = venueName
            };
        }

        public static Venue Update(Venue venue, Country country, string venueName)
        {
            venue.Country = country;
            venue.VenueName = venueName;

            return venue;
        }

        public static Venue AddOrUpdate(IFDBContext db, Guid? venueId, Country country, string venueName)
        {
            var localQuery = from venue in db.Venues.Local
                             where venue.VenueId == (venueId ?? Guid.Empty)
                             select venue;

            var query = from venue in db.Venues
                        where venue.VenueId == (venueId ?? Guid.Empty)
                        select venue;

            if (localQuery.Count() == 1)
                return Update(localQuery.Single(), country, venueName);
            else if (query.Count() == 1)
                return Update(query.Single(), country, venueName);
            else
            {
                var newRow = CreateNew(country, venueName);
                db.Venues.Add(newRow);
                return newRow;
            }
        }
    }
}
